<template>
  <div class="attendance-check-in">
    <el-card class="box-card">
      <!-- 页面标题 -->
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.checkIn') }}</span>
      </div>

      <!-- 主要内容区域 -->
      <div class="content">
        <!-- 当前时间显示 -->
        <div class="current-time">
          <h3>{{ $t('attendance.currentTime') }}：{{ currentTime }}</h3>
        </div>

        <!-- 课程选择和打卡区域 -->
        <div class="course-selection" v-if="courses.length > 0">
          <el-form :model="checkInForm" label-width="100px" ref="checkInForm">
            <!-- 课程选择 -->
            <el-form-item :label="$t('attendance.selectCourse')" prop="courseId" :rules="[{ required: true, message: $t('attendance.pleaseSelectCourse'), trigger: 'change' }]">
              <el-select v-model="checkInForm.courseId" :placeholder="$t('attendance.pleaseSelectCourse')" @change="handleCourseChange">
                <el-option
                  v-for="course in courses"
                  :key="course.id"
                  :label="course.name"
                  :value="course.id">
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 课程信息展示 -->
            <div v-if="selectedCourse" class="course-info">
              <el-descriptions :column="1" border>
                <el-descriptions-item :label="$t('attendance.courseName')">{{ selectedCourse.name }}</el-descriptions-item>
                <el-descriptions-item :label="$t('attendance.courseTime')">
                  {{ formatTime(selectedCourse.startTime) }} - {{ formatTime(selectedCourse.endTime) }}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('attendance.courseLocation')">{{ selectedCourse.location }}</el-descriptions-item>
                <el-descriptions-item :label="$t('attendance.checkInTime')">{{ checkInTimeRange }}</el-descriptions-item>
                <el-descriptions-item :label="$t('attendance.expectedStatus')" v-if="selectedCourse && courseConfig">
                  <el-tag :type="getStatusTagType(expectedStatus)">
                    {{ $t('attendance.' + expectedStatus) }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 打卡按钮和状态提示 -->
            <el-form-item v-if="selectedCourse">
              <el-button 
                type="primary" 
                @click="handleCheckIn" 
                :loading="loading"
                :disabled="!canCheckIn">
                {{ $t('attendance.checkIn') }}
              </el-button>
              <div v-if="!canCheckIn" class="warning-text">
                <div v-if="!isInCheckInTime">{{ $t('attendance.notInCheckInTime') }}</div>
                <div v-if="!isNearLocation && locationRequired">{{ $t('attendance.notInValidCheckInRange') }}</div>
              </div>
              <div v-else-if="expectedStatus !== 'normal'" class="warning-text">
                <span>{{ $t('attendance.willBeMarkedAs', { status: $t('attendance.' + expectedStatus) }) }}</span>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 无课程提示 -->
        <div v-else class="no-course">
          <el-empty :description="$t('attendance.noAvailableCourses')"></el-empty>
        </div>

        <!-- 打卡结果提示 -->
        <div v-if="checkInResult" class="check-in-result">
          <el-alert
            :title="checkInResult.msg"
            :type="checkInResult.success ? 'success' : 'error'"
            :description="checkInResult.description"
            show-icon>
          </el-alert>
          
          <div v-if="checkInResult.success && checkInResult.status" class="status-info">
            <el-alert
              :title="$t('attendance.attendanceStatus') + ': ' + $t('attendance.' + checkInResult.status)"
              :type="getStatusAlertType(checkInResult.status)"
              show-icon>
            </el-alert>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'AttendanceCheckIn',
  
  data() {
    return {
      currentTime: '',
      timer: null,
      courses: [],
      selectedCourse: null,
      checkInForm: {
        courseId: '',
        userId: this.getUserId()
      },
      loading: false,
      checkInResult: null,
      userLocation: {
        latitude: null,
        longitude: null
      },
      courseConfig: null,
      locationRequired: false,
      isInCheckInTime: false,
      isNearLocation: false,
      expectedStatus: 'normal'
    }
  },

  computed: {
    checkInTimeRange() {
      if (this.courseConfig) {
        return `${this.formatTime(this.courseConfig.checkInTime)} - ${this.formatTime(this.courseConfig.checkInEndTime)}`
      }
      return this.$t('attendance.notSet')
    },

    canCheckIn() {
    //   return true
      if (this.locationRequired) {
        return this.isInCheckInTime && this.isNearLocation
      }
      return this.isInCheckInTime
    }
  },

  created() {
    this.initPage()
  },

  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },

  methods: {
    // 初始化页面
    async initPage() {
      try {
        // 更新当前时间并设置定时器
        this.updateCurrentTime()
        this.timer = setInterval(this.updateCurrentTime, 1000)
        
        // 获取用户位置
        this.getUserLocation()
        
        // 获取学生课程
        await this.loadStudentCourses()
        
        // 如果没有课程，显示提示
        if (this.courses.length === 0) {
          //console.log('没有可打卡课程')
        } else {
          //console.log(`找到 ${this.courses.length} 门可打卡课程`)
        }
      } catch (error) {
        console.error('初始化页面出错:', error)
        this.$message.error(this.$t('common.loadFailedRetry'))
      }
    },

    // 获取用户ID
    getUserId() {
      try {
        const userInfo = sessionStorage.getItem('userInfo')
        if (!userInfo) {
          console.warn('未找到用户信息')
          return null
        }
        const userData = JSON.parse(userInfo)
        //console.log('用户信息:', userData)
        return userData.userId
      } catch (error) {
        console.error('获取用户ID出错:', error)
        return null
      }
    },

    // 更新当前时间
    updateCurrentTime() {
      const now = new Date()
      this.currentTime = now.toLocaleString()
      this.checkAttendanceTime()
    },

    // 检查是否在签到时间范围内并确定可能的考勤状态
    checkAttendanceTime() {
      if (!this.selectedCourse || !this.courseConfig) {
        this.isInCheckInTime = false
        this.expectedStatus = 'normal'
        return
      }

      try {
        const now = new Date()
        const currentHour = now.getHours()
        const currentMinute = now.getMinutes()
        
        // 确保签到时间存在
        if (!this.courseConfig.checkInTime || !this.courseConfig.checkInEndTime) {
          console.warn(this.$t('attendance.checkInTimeNotSet'))
          this.isInCheckInTime = false
          this.expectedStatus = 'normal'
          return
        }
        
        const checkInTime = this.parseTime(this.courseConfig.checkInTime)
        const checkInEndTime = this.parseTime(this.courseConfig.checkInEndTime)
        const courseStartTime = this.parseTime(this.selectedCourse.startTime)
        
        // 将字符串时间转换为分钟值
        const getMinutes = (timeStr) => {
          const [hours, minutes] = timeStr.split(':').map(Number)
          return hours * 60 + minutes
        }
        
        const currentValue = currentHour * 60 + currentMinute
        const startValue = getMinutes(checkInTime)
        const endValue = getMinutes(checkInEndTime)
        const courseStartValue = getMinutes(courseStartTime)
        
        // 检查是否在签到时间范围内
        this.isInCheckInTime = currentValue >= startValue && currentValue <= endValue
        
        // 确定考勤状态
        if (currentValue < startValue) {
          // 尚未到签到时间
          this.expectedStatus = 'normal'
        } else if (currentValue <= endValue) {
          // 在签到时间范围内
          this.expectedStatus = 'normal'
        } else if (currentValue <= courseStartValue) {
          // 过了签到时间但课程还未开始
          this.expectedStatus = 'late'
        } else {
          // 课程已经开始
          const lateMinutes = currentValue - courseStartValue
          // 如果迟到超过课程时长的一半，则算作旷课
          if (lateMinutes > 30) {
            this.expectedStatus = 'absent'
          } else {
            this.expectedStatus = 'late'
          }
        }
      } catch (error) {
        console.error('检查签到时间出错:', error)
        this.isInCheckInTime = false
        this.expectedStatus = 'normal'
      }
    },

    // 加载学生课程
    async loadStudentCourses() {
      try {
        const data = await this.$axios.get(`/course/student/${this.checkInForm.userId}`)
        //console.log(data)
        if (data.code === 200) {
          this.courses = data.data || []
        } else {
          this.$message.error(this.$t('course.getCoursesError'))
        }
      } catch (error) {
        console.error('获取课程信息失败:', error)
        this.$message.error(this.$t('course.getCoursesError'))
      }
    },

    // 处理课程选择变化
    async handleCourseChange(courseId) {
      try {
        this.selectedCourse = null
        this.courseConfig = null
        this.expectedStatus = 'normal'
        
        if (!courseId) return
        
        //console.log('选择课程ID:', courseId)
        
        // 并行加载课程详情和考勤配置
        const [courseDetailResp, attendanceConfigResp] = await Promise.all([
          this.loadCourseDetail(courseId),
          this.loadAttendanceConfig(courseId)
        ])
        
        //console.log('课程详情:', courseDetailResp)
        //console.log('考勤配置:', attendanceConfigResp)
        
        // 确保数据已加载并设置到组件状态
        if (courseDetailResp && attendanceConfigResp) {
          this.checkAttendanceTime()
          this.checkLocation()
        }
      } catch (error) {
        console.error('处理课程选择变化出错:', error)
        this.$message.error(this.$t('course.getCoursesError'))
      }
    },

    // 加载课程详情
    async loadCourseDetail(courseId) {
      try {
        const data = await this.$axios.get(`/course/detail/${courseId}`)
        if (data.code === 200 && data.data) {
          this.selectedCourse = data.data
          return data.data
        } else {
          this.$message.error(data.msg || this.$t('course.getCoursesError'))
          return null
        }
      } catch (error) {
        console.error('获取课程详情失败:', error)
        this.$message.error(this.$t('course.getCoursesError'))
        return null
      }
    },

    // 加载考勤配置
    async loadAttendanceConfig(courseId) {
      try {
        const data = await this.$axios.get(`/attendance/config/course?courseId=${courseId}`)
        if (data.code === 200 && data.data) {
          this.courseConfig = data.data
          this.locationRequired = !!this.courseConfig.locationRequired
          return data.data
        } else {
            if(data.data == null){
                this.$message.error(this.$t('attendance.getConfigError'))
            }else{
                this.$message.error(data.msg || this.$t('attendance.getConfigError'))
            }
          return null
        }
      } catch (error) {
        console.error('获取考勤配置失败:', error)
        this.$message.error(this.$t('attendance.getConfigError'))
        return null
      }
    },

    // 获取用户位置
    getUserLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          position => {
            this.userLocation = {
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            }
            this.checkLocation()
          },
          error => {
            console.error('获取位置信息失败:', error)
            this.$message.warning(this.$t('attendance.locationNotAvailable'))
          }
        )
      } else {
        this.$message.warning(this.$t('attendance.browserLocationNotSupported'))
      }
    },

    // 检查位置
    checkLocation() {
      if (!this.locationRequired) {
        this.isNearLocation = true
        return
      }
      
      if (!this.selectedCourse || !this.courseConfig) {
        this.isNearLocation = false
        return
      }
      
      try {
        // 检查用户位置是否获取成功
        if (!this.userLocation.latitude || !this.userLocation.longitude) {
          console.warn(this.$t('attendance.userLocationNotObtained'))
          this.isNearLocation = false
          return
        }
        
        // 检查课程配置中是否包含位置信息
        if (!this.courseConfig.locationLatitude || !this.courseConfig.locationLongitude) {
          console.warn(this.$t('attendance.courseLocationNotSet'))
          this.isNearLocation = true // 如果未设置位置，默认允许打卡
          return
        }
        
        const distance = this.calculateDistance(
          this.userLocation.latitude,
          this.userLocation.longitude,
          this.courseConfig.locationLatitude,
          this.courseConfig.locationLongitude
        )
        
        //console.log('用户位置:', this.userLocation)
        //console.log('课程位置:', {
        //  lat: this.courseConfig.locationLatitude,
        //  lng: this.courseConfig.locationLongitude
        //})
        //console.log('距离(米):', distance)
        //console.log('有效距离(米):', this.courseConfig.validDistance)
        
        this.isNearLocation = distance <= (this.courseConfig.validDistance || 200)
        //console.log('是否在有效打卡范围内:', this.isNearLocation)
      } catch (error) {
        console.error('检查位置出错:', error)
        this.isNearLocation = false
      }
    },

    // 计算两点之间的距离
    calculateDistance(lat1, lon1, lat2, lon2) {
      const R = 6371e3 // 地球半径（米）
      const φ1 = this.toRadians(lat1)
      const φ2 = this.toRadians(lat2)
      const Δφ = this.toRadians(lat2 - lat1)
      const Δλ = this.toRadians(lon2 - lon1)

      const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
                Math.cos(φ1) * Math.cos(φ2) *
                Math.sin(Δλ/2) * Math.sin(Δλ/2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))

      return R * c // 返回距离（米）
    },

    // 角度转弧度
    toRadians(degrees) {
      return degrees * Math.PI / 180
    },

    // 处理打卡
    async handleCheckIn() {
      if (!this.checkInForm.courseId) {
        this.$message.warning(this.$t('attendance.pleaseSelectCourse'))
        return
      }

      this.loading = true
      try {
        const params = {
          courseId: this.checkInForm.courseId,
          userId: this.checkInForm.userId,
          locationLatitude: this.userLocation.latitude,
          locationLongitude: this.userLocation.longitude,
          expectedStatus: this.expectedStatus
        }

        const data = await this.$axios.post('/attendance/checkIn', params)
        
        if (data.code === 200) {
          // 获取后端返回的实际打卡状态
          const attendanceStatus = data.data && data.data.status ? data.data.status : this.expectedStatus
          
          this.checkInResult = {
            success: true,
            msg: this.$t('attendance.checkInSuccess'),
            description: `${this.$t('attendance.checkTime')}: ${new Date().toLocaleTimeString()}`,
            status: attendanceStatus
          }
          
          // 根据不同状态显示不同的提示信息
          if (attendanceStatus === 'normal') {
            this.$message.success(this.$t('attendance.checkInSuccess'))
          } else if (attendanceStatus === 'late') {
            this.$message.warning(this.$t('attendance.checkInLate'))
          } else if (attendanceStatus === 'absent') {
            this.$message.error(this.$t('attendance.checkInAbsent'))
          } else {
            this.$message.success(this.$t('attendance.checkInSuccess'))
          }
        } else {
          this.checkInResult = {
            success: false,
            msg: this.$t('attendance.checkInFailed'),
            description: data.msg || this.$t('common.unknown')
          }
          this.$message.error(data.msg || this.$t('attendance.checkInFailed'))
        }
      } catch (error) {
        console.error('打卡失败:', error)
        this.checkInResult = {
          success: false,
          msg: this.$t('attendance.checkInFailed'),
          description: error.message || this.$t('common.operationFailedRetry')
        }
        this.$message.error(this.$t('attendance.checkInFailed'))
      } finally {
        this.loading = false
      }
    },

    // 获取状态对应的标签类型
    getStatusTagType(status) {
      const types = {
        normal: 'success',
        late: 'warning',
        absent: 'danger',
        leave: 'info',
        earlyLeave: 'warning'
      }
      return types[status] || 'info'
    },
    
    // 获取状态对应的提示类型
    getStatusAlertType(status) {
      const types = {
        normal: 'success',
        late: 'warning',
        absent: 'error',
        leave: 'info',
        earlyLeave: 'warning'
      }
      return types[status] || 'info'
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '--:--'
      
      if (typeof time === 'string') {
        return time
      }
      
      if (typeof time === 'object' && time.hour !== undefined && time.minute !== undefined) {
        return `${time.hour}:${time.minute.toString().padStart(2, '0')}`
      }
      
      return '--:--'
    },

    // 解析时间
    parseTime(timeStr) {
      if (!timeStr || typeof timeStr !== 'string') {
        return '00:00'
      }
      
      try {
        const [hour, minute] = timeStr.split(':').map(Number)
        return `${hour || 0}:${(minute || 0).toString().padStart(2, '0')}`
      } catch (e) {
        console.error('解析时间错误:', e, timeStr)
        return '00:00'
      }
    }
  }
}
</script>

<style scoped>
.attendance-check-in {
  padding: 20px;
}

.content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.current-time {
  text-align: center;
  margin-bottom: 20px;
}

.course-info {
  margin: 20px 0;
}

.warning-text {
  color: #E6A23C;
  margin-top: 10px;
  font-size: 14px;
}

.check-in-result {
  margin-top: 20px;
}

.status-info {
  margin-top: 10px;
}

.no-course {
  display: flex;
  justify-content: center;
  margin: 40px 0;
}

.el-descriptions {
  margin: 20px 0;
}

.el-alert {
  margin: 10px 0;
}
</style>